package com.utils.network2.gank.parser;


import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;


import com.utils.network2.gank.entity.GankResponse;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import rxhttp.wrapper.annotation.Parser;
import rxhttp.wrapper.entity.ParameterizedTypeImpl;
import rxhttp.wrapper.exception.ParseException;
import rxhttp.wrapper.parse.AbstractParser;

/**
 * Response<List<T>> 数据解析器,解析完成对Response对象做判断,如果ok,返回数据 List<T>
 *
 * @param <T>
 */
@Parser(name = "GankResponseList")
public class ResponseListParser<T> extends AbstractParser<LiveData<List<T>>> {
    protected ResponseListParser() {
        super();
    }

    public ResponseListParser(Class<T> type) {
        super(type);
    }

    @Override
    public MutableLiveData<List<T>> onParse(okhttp3.Response response) throws IOException {
        final Type type = ParameterizedTypeImpl.get(GankResponse.class, List.class, mType); //获取泛型类型
        GankResponse<List<T>> data = convert(response, type);
        List<T> results = data.getResults(); //获取data字段
        MutableLiveData<List<T>> list = new MutableLiveData<>(results);
        //list.postValue(results);
        if (data.isError()) {  //code不等于0，说明数据不正确，抛出异常
            throw new ParseException("-1", "", response);
        }
        return list;
    }
}
